<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=4lbvS1ONrdptacjusrTqAsdjG1GSGXQN"></script>
    <title>城市列表控件</title>
</head>
<body>
    <div id="allmap"></div>
    <div id="merchantListDiv"></div>
</body>
</html>
<script type="text/javascript">
var currentCity = {
	city: "北京市",
	title: "北京市",
	point: {
		lng: 116.413554,
		lat: 39.911013
	}
}

var mp = new BMap.Map("allmap")
var point = new BMap.Point(currentCity.point.lng, currentCity.point.lat)
mp.centerAndZoom(point, 13)
mp.enableScrollWheelZoom()
mp.enableInertialDragging()
mp.enableContinuousZoom()

// 创建地址解析器实例
var myGeo = new BMap.Geocoder()

var driving = new BMap.DrivingRoute(mp, {renderOptions: {map: mp, autoViewport: true}})
var transit = new BMap.TransitRoute(mp, {renderOptions: {map: mp}})

// 选择城市
var cityListControl = new BMap.CityListControl({
    anchor: BMAP_ANCHOR_TOP_LEFT,
    offset: new BMap.Size(10, 20),
    // 切换城市之前事件
    onChangeBefore: function(){
		console.log('before', currentCity)
    },
    // 切换城市之后事件
    onChangeAfter: function(){
      console.log('after', currentCity)
    },
	onChangeSuccess: function(data){
		currentCity.city = data.city
		currentCity.title = data.title
		currentCity.point = data.point

		mp.setCurrentCity(currentCity.title)
		myAddressSearchControl.setAutocompletePoint(new BMap.Point(currentCity.point.lng, currentCity.point.lat))
		getSurroundingMerchant(new BMap.Point(currentCity.point.lng, currentCity.point.lat))
	}
})
mp.addControl(cityListControl)


function MerchantListControl(){
	this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT
	this.defaultOffset = new BMap.Size(10, 20)
}
MerchantListControl.prototype = new BMap.Control()
MerchantListControl.prototype.initialize = function(map){
	var _this = this

	var titleDiv = document.createElement("div")
	titleDiv.style.textAlign = "center"
	titleDiv.style.marginBottom = "12px"
	titleDiv.appendChild(document.createTextNode("机构管理"))

	this.input = document.createElement("input")

	this.formShowDiv = document.createElement("div")

	var button = document.createElement("button")
	button.style.marginTop = "8px"
	button.appendChild(document.createTextNode("添加机构"))
	button.onclick = function () {
		var merName = _this.input.value
		if (!merName) {
			alert("机构名称不能为空！")
		} else if (!_this.address && _this.point.lat && _this.point.lng) {
			alert("请在地图选择位置！")
		} else {
			post("/api/merchant/add", {
				merchantName: merName,
				business: _this.business,
				addressComponents: _this.addressComponents,
				surroundingPois: _this.surroundingPois,
				point: _this.point
			}, function (code, data) {
				if (code) {
					getSurroundingMerchant(_this.point)
				} else {
					alert("异常")
				}
			})
		}
	}

	this.formDiv = document.createElement("div")
	this.formDiv.style.display = "none"
	this.formDiv.appendChild(document.createTextNode("机构名称："))
	this.formDiv.appendChild(this.input)
	this.formDiv.appendChild(this.formShowDiv)
	this.formDiv.appendChild(button)

	this.merchantListUl = new MerchantListUl()
	this.merchantListUl.setCallback(function (value) {
		post("/api/merchant/delete", {
			id: value
		}, function (code, data) {
			if (code) {
				getSurroundingMerchant(_this.point)
			} else {
				alert("delete异常")
			}
		})
	})

	this.listDiv = document.createElement("div")
	this.listDiv.style.marginTop = "10px"
	this.listDiv.style.display = "none"
	this.listDiv.appendChild(this.merchantListUl.container)

	this.container = document.createElement("div")
	this.container.style.width = "380px"
	this.container.style.minHeight = "60px"
	this.container.style.padding = "10px 10px"
	this.container.style.border = "1px solid gray"
	this.container.style.backgroundColor = "white"
	this.container.appendChild(titleDiv)
	this.container.appendChild(this.formDiv)
	this.container.appendChild(this.listDiv)

	// map.getContainer().appendChild(this.container)
	document.getElementById("merchantListDiv").appendChild(this.container)

	return this.container
}
MerchantListControl.prototype.showAdd = function(info){
	this.address = info.address
	this.business = info.business
	this.addressComponents = info.addressComponents
	this.surroundingPois = info.surroundingPois
	this.point = info.point

	var content = ""
	content += "所属商圈：" + this.business + "<br/>"
	content += "地址：" + this.address + "<br/>"
	if (this.surroundingPois.length > 0) {
	content += "周围地标：" + this.surroundingPois[0].title + "<br/>"
	}

	this.input.value = ""
	this.formShowDiv.innerHTML = content
	this.formDiv.style.display = "block"
}
MerchantListControl.prototype.showMerchantList = function(data, point){
	deleteAllMerchantPoint()
	if (data && data.code == 1) {
		var list = data.params
		if (list && list.length > 0) {
			this.merchantListUl.load(list, point)
			this.listDiv.style.display = "block"
		} else {
			this.listDiv.style.display = "none"
		}
	} else {
		this.listDiv.style.display = "none"
		alert(data.msg)
	}
}
MerchantListControl.prototype.setCurrentPoint = function(point){
	this.point = point
}
var merchantListControl = new MerchantListControl()
mp.addControl(merchantListControl)


// 搜索地址
function AddressSearchControl(){
  this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT
  this.defaultOffset = new BMap.Size(10, 50)
}
AddressSearchControl.prototype = new BMap.Control()
AddressSearchControl.prototype.initialize = function(map){
  var serachListUl = new SerachListUl()

  var input = document.createElement("input")
  input.style.height = "20px"
  /*
  input.oninput = function (e) {
	var keyword = this.value
	if (keyword) {
		var options = {
			onSearchComplete: function(results){
				// 判断状态是否正确
				if (local.getStatus() == BMAP_STATUS_SUCCESS){
					var showData = [];
					for (var i = 0; i < results.getCurrentNumPois(); i ++){
						var item = results.getPoi(i)
						showData.push(item);
					}
					
	                serachListUl.load(showData)
				} else {
	                serachListUl.hidden()
				}
			}
		};
		var local = new BMap.LocalSearch(map, options);
		local.search(keyword)
	} else {
	  serachListUl.hidden()
	}
  }
  */
  this.autocomplete = new BMap.Autocomplete({
	"input": input,
	"location": new BMap.Point(currentCity.point.lng, currentCity.point.lat)
  })

  serachListUl.setCallback(function (value) {
    input.value = value
  })

  var searchButton = document.createElement("button")
  searchButton.appendChild(document.createTextNode("位置搜索"));
  searchButton.style.height = "26px"
  searchButton.style.marginLeft = "6px"
  searchButton.onclick = function(e){
	var city = currentCity.title
	var address = input.value

	// 将地址解析结果显示在地图上,并调整地图视野
	myGeo.getPoint(address, function(point){
		if (point) {
			deleteAllUserPoint()

			var addMerchantMarker = function(e, ee, marker){
				var pooint = marker.getPosition()
				myGeo.getLocation(pooint, function(res){
					var address = res.address
					var business = res.business
					var addressComponents = res.addressComponents
					var surroundingPois = res.surroundingPois
					var point = res.point

					merchantListControl.showAdd({address, business, addressComponents, surroundingPois, point})
				})
			}
			//创建右键菜单
			var markerMenu=new BMap.ContextMenu()
			markerMenu.addItem(new BMap.MenuItem('添加到机构库', addMerchantMarker))

			var marker = new BMap.Marker(point)
			// marker.setAnimation(BMAP_ANIMATION_BOUNCE) // 跳动的动画
			marker.enableDragging() // 可拖拽
			marker.typee = "user"
			marker.setTop(true)
			marker.addContextMenu(markerMenu)
			marker.addEventListener("click", function(){
				var _this = this
				var pooint = _this.getPosition()
				showAddressInfo(pooint, function (infoWindow) {
					_this.openInfoWindow(infoWindow)
				})
			})
			marker.addEventListener("dragstart", function(){
				// this.closeInfoWindow()
			})
			marker.addEventListener("dragend", function(){
				var _this = this
				_this.closeInfoWindow()
				var pooint = _this.getPosition()
				showAddressInfo(pooint, function (infoWindow) {
					_this.openInfoWindow(infoWindow)
				})

				// 查询坐标附近的机构
				getSurroundingMerchant(pooint)
			})

			map.centerAndZoom(point, 15)
			map.addOverlay(marker)

			merchantListControl.setCurrentPoint(point)
			myAddressSearchControl.setAutocompletePoint(point)
			// 查询坐标附近的机构
			getSurroundingMerchant(point)
		}else{
			alert("您选择地址没有解析到结果!")
		}
	}, city)
  }

  var clearButton = document.createElement("button")
  clearButton.appendChild(document.createTextNode("搜索框清空"))
  clearButton.style.height = "26px"
  clearButton.style.marginLeft = "6px"
  clearButton.onclick = function(e){
	input.value = ''
	serachListUl.hidden()
  }

  var div = document.createElement("div")
  div.appendChild(input)
  div.appendChild(searchButton)
  div.appendChild(clearButton)
  div.appendChild(serachListUl.container)

  map.getContainer().appendChild(div)
  return div;
}
AddressSearchControl.prototype.setAutocompletePoint = function (point) {
	this.autocomplete.setLocation(point)
}
// 创建控件
var myAddressSearchControl = new AddressSearchControl()
// 添加到地图当中
mp.addControl(myAddressSearchControl)

// 方法
function deleteAllUserPoint(){
	var allOverlay = mp.getOverlays();
	for (var i = 0; i < allOverlay.length; i++){
		if(allOverlay[i].typee == "user"){
			mp.removeOverlay(allOverlay[i]);
		}
	}
}

function deleteAllMerchantPoint(){
	var allOverlay = mp.getOverlays();
	for (var i = 0; i < allOverlay.length; i++){
		if(allOverlay[i].typee == "merchant"){
			mp.removeOverlay(allOverlay[i]);
		}
	}
}

var showAddressInfo = function (point, callback, options, merName) {
	myGeo.getLocation(point, function(res){
		var address = res.address
		var business = res.business
		var addressComponents = res.addressComponents
		var surroundingPois = res.surroundingPois

		var content = ""
		if (merName) {
			content += "<br/>机构名称：" + merName
		}
		content += "<br/>所属商圈：" + business
		content += "<br/>地址：" + address
		if (surroundingPois.length > 0) {
		content += "<br/>周围地标：" + surroundingPois[0].title
		}

		var opts = options || {
			width : 260,
			height: 160
		}
		var infoWindow = new BMap.InfoWindow(content, opts)
		callback.call(callback, infoWindow)
	})
}

function getSurroundingMerchant(point) {
	point = point || new BMap.Point(currentCity.point.lng, currentCity.point.lat)
	// 查询坐标附近的机构
	myGeo.getLocation(point, function(res){
		var address = res.address
		var business = res.business
		var addressComponents = res.addressComponents
		var surroundingPois = res.surroundingPois

		post("/api/merchant/list", {
			searchMap: [
				{
					searchKey: "province",
					searchValue: addressComponents.province
				},
				{
					searchKey: "city",
					searchValue: addressComponents.city
				}
				/*,
				{
					searchKey: "district",
					searchValue: addressComponents.district
				}
				*/
			]
		}, function (code, data) {
			if (code) {
				merchantListControl.showMerchantList(JSON.parse(data), point)
			} else {
				alert("list异常")
			}
		})
	})
}

function SerachListUl () {
  var ul = document.createElement("ul")
  ul.style.margin = "0px"
  ul.style.padding = "10px 20px"
  ul.style.listStyleType = "none"

  this.container = document.createElement("div")
  this.container.style.width = "300px"
  this.container.style.backgroundColor = "white"
  this.container.style.border = "1px solid gray";
  this.container.style.display = "none"

  this.container.appendChild(ul)

  this.show = function () {
    this.container.style.display = "block"
  }

  this.hidden = function () {
    this.container.style.display = "none"
  }

  this.load = function (data) {
      var _this = this
	  ul.innerHTML = ""
	  for (var i = 0; i < data.length; i++) {
	      var item = data[i]
		  var li = document.createElement("li")
		  li.style.fontSize = "15px"
		  li.style.margin = "5px 0px"
		  li.style.cursor = "pointer"
		  li.title = item.title
		  li.appendChild(document.createTextNode(item.title))
		  li.onclick = function(){
			if (_this.callback) {
			  _this.callback.call(_this.callback, this.title)
			}
		  }

		  ul.appendChild(li)
	  }
	  this.show()
  }

  this.setCallback = function (callback) {
    this.callback = callback
  }
}

function MerchantListUl () {
  var ul = document.createElement("ul")
  ul.style.maxHeight = "444px"
  ul.style.margin = "0px"
  ul.style.padding = "5px 12px"
  ul.style.listStyleType = "none"
  ul.style.overflow = "auto"
  ul.onscroll = function (event) {
	event.stopPropagation()
	console.log(666)
  }

  this.container = document.createElement("div")
  this.container.style.width = "380px"
  this.container.style.backgroundColor = "#eeeeee"

  this.container.appendChild(ul)

  this.load = function (list, point) {
      var _this = this
	  ul.innerHTML = ""

	  let length = list.length || 0
	  if (length > 0) {
		// 计算距离
		for (var i = 0; i < length; i++) {
			var item = list[i]
			var tPoint = new BMap.Point(item.lng, item.lat);
			item.distance = mp.getDistance(tPoint, point).toFixed(2)
		}

		// 根据排序排序
		list.sort(function(a, b){
			return a.distance - b.distance
		})

		var merchantMarkerArr = []
		var merchantLiArr = []

		// 在地图生成机构坐标点
		for (var i = 0; i < length; i++) {
			var item = list[i]
			var tPoint = new BMap.Point(item.lng, item.lat)

			var deleteMerchantMarker = function(e, ee, marker){
				if (_this.callback) {
					_this.callback.call(_this.callback, marker.item.id)
				}
			}
			//创建右键菜单
			var markerMenu=new BMap.ContextMenu()
			markerMenu.addItem(new BMap.MenuItem('删除机构', deleteMerchantMarker))

			var marker = new BMap.Marker(tPoint)
			// marker.setLabel(new BMap.Label(item.merchant_name, {offset: new BMap.Size(15, 30)}))
			marker.setIcon(new BMap.Icon("img/coordinate.png", new BMap.Size(30, 30), {anchor: new BMap.Size(15, 30)}))
			// marker.setAnimation(BMAP_ANIMATION_BOUNCE) // 跳动的动画
			marker.addContextMenu(markerMenu)
			marker.disableDragging() // 不可拖拽
			marker.typee = "merchant"
			marker.index = i
			marker.item = item
			marker.addEventListener("click", function(){
				var _this = this
				var pooint = _this.getPosition()
				showAddressInfo(pooint, function (infoWindow) {
					_this.openInfoWindow(infoWindow)
				}, {
					width : 260,
					height: 160,
					offset: new BMap.Size(0, -30)
				}, _this.item.merchant_name)
				selectItemFunc(_this.index, merchantMarkerArr, merchantLiArr)
			})

			merchantMarkerArr.push(marker)
			mp.addOverlay(marker)
		}

		for (var i = 0; i < length; i++) {
			var item = list[i]

			var content = item.merchant_name + "（" + item.district + item.street + item.streetNumber + ")" + "， 距离：" + item.distance + "米"
			var contentText = document.createTextNode(content)

			var span = document.createElement("span")
			span.style.width = "256px"
			span.style.display = "inline-block"
			span.appendChild(contentText)

			var button = document.createElement("button")
			button.style.cursor = "pointer"
			button.style.display = "block"
			button.id = item.id
			button.onclick = function(event){
				event.stopPropagation()
				if (_this.callback) {
					_this.callback.call(_this.callback, this.id)
				}
			}
			button.appendChild(document.createTextNode("删除"))

			var transitRouteButton = document.createElement("button")
			transitRouteButton.style.cursor = "pointer"
			transitRouteButton.style.display = "block"
			transitRouteButton.id = item.id
			transitRouteButton.index = i
			transitRouteButton.onclick = function(event){
				event.stopPropagation()
				
				let tMarker = merchantMarkerArr[this.index]
				var uPoint = point
				var tPoint = tMarker.getPosition()

				transit.search(uPoint, tPoint)
			}
			transitRouteButton.appendChild(document.createTextNode("公交导航"))

			var drivingRouteButton = document.createElement("button")
			drivingRouteButton.style.cursor = "pointer"
			drivingRouteButton.style.display = "block"
			drivingRouteButton.id = item.id
			drivingRouteButton.index = i
			drivingRouteButton.onclick = function(event){
				event.stopPropagation()
				
				let tMarker = merchantMarkerArr[this.index]
				var uPoint = point
				var tPoint = tMarker.getPosition()

				driving.search(uPoint, tPoint)
			}
			drivingRouteButton.appendChild(document.createTextNode("驾车导航"))

			var buttonDiv = document.createElement("div")
			buttonDiv.style.float = "right"
			buttonDiv.style.display = "inline-grid"
			// buttonDiv.appendChild(button)
			buttonDiv.appendChild(transitRouteButton)
			buttonDiv.appendChild(drivingRouteButton)

			var li = document.createElement("li")
			li.style.fontSize = "15px"
			li.style.margin = "5px 0px"
			li.style.padding = "5px"
			li.style.border = "dashed 1px #000066"
			li.style.clear = "both"
			li.style.display = "inline-block"
			li.index = i
			li.onclick = function(){
				selectItemFunc(this.index, merchantMarkerArr, merchantLiArr)
			}
			li.appendChild(span)
			li.appendChild(buttonDiv)

			merchantLiArr.push(li)
			ul.appendChild(li)
		}

		var selectItemFunc = function (index, merchantMarkerArr, merchantLiArr) {
			for (var i = 0; i < merchantMarkerArr.length; i++) {
				var tMarker = merchantMarkerArr[i]
				var tLi = merchantLiArr[i]
				if (i == index) {
					tMarker.setAnimation(BMAP_ANIMATION_BOUNCE)
					tLi.style.border = "dashed 1.5px #009900"
				} else {
					tMarker.setAnimation(null)
					tLi.style.border = "dashed 1px #000066"
				}
			}
		}
	  }
  }

  this.setCallback = function (callback) {
    this.callback = callback
  }
}

function post(url, data, callback) {
	var xhr = new XMLHttpRequest()
	xhr.open("POST", url, true)
	xhr.setRequestHeader("Content-type", "application/json")
	xhr.setRequestHeader("kbn-version", "5.3.0")
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				callback(1, xhr.responseText)
				return
			} else {
				// callback(0)
			}
		} else {
			// callback(0)
		}
	}
	xhr.send(JSON.stringify(data))
}
</script>